package com.appspot.yusupova;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.yusupova.verses.VerseMap;
import com.google.appengine.repackaged.com.google.common.util.Base64;

@SuppressWarnings("serial")
public final class GetAllVersesServlet extends AdminHttpServlet {
    
    private static final Logger logger = Logger.getLogger(GetAllVersesServlet.class.getName());
    
    protected void doAuthorizedPost(HttpServletRequest req, HttpServletResponse resp, 
            PrintWriter writer) throws IOException {
        String allVerses = VerseMap.getAll();
        if (allVerses != null) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ZipOutputStream zos = new ZipOutputStream(baos);
                try {
                    ZipEntry entry = new ZipEntry("verses.txt");
                    zos.putNextEntry(entry);
                    zos.write(allVerses.getBytes("UTF-8"));
                } finally {
                    zos.close();
                }
                String encoded = Base64.encode(baos.toByteArray());
                writer.println(encoded);
                
                /*
                Properties props = new Properties();
                Session session = Session.getDefaultInstance(props, null);
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("roosya2008@gmail.com", "Owner"));
                msg.addRecipient(Message.RecipientType.TO,
                                 new InternetAddress("roosya@pochta.ru", ""));
                msg.setSubject("All verses");
                msg.setText(allVerses);
                Transport.send(msg);
                writer.println("all verses have been sent");
                */
                
            } catch (Exception e) {
                e.printStackTrace();
                logger.log(Level.SEVERE, "Cannot send email!", e);
                writer.println("Error occured:" + e.toString() + " (" + e.getMessage() + ")");
            }
        } else {
            writer.println("There are no verses to send");
        }
    }
    
}
